<script>
import { Codemirror } from "vue-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import { oneDark } from "@codemirror/theme-one-dark";
import { reactive, ref, toRefs } from "vue";
import { Fileinfo, write } from "@/api/worksheet";
import { message } from "@/utils/message";

export default {
  components: {
    Codemirror
  },
  setup() {
    const code = ref(``);
    const extensions = [javascript(), oneDark];
    // 计算字符串的字节长度
    const getStringByteLength = str => {
      let len = 0;
      for (let i = 0; i < str.length; i++) {
        const charCode = str.charCodeAt(i);
        if (charCode <= 0x007f) {
          len += 1;
        } else if (charCode <= 0x07ff) {
          len += 2;
        } else if (charCode <= 0xffff) {
          len += 3;
        } else {
          len += 4;
        }
      }
      return len;
    };
    const getFilinfo = async (file, id) => {
      console.log(file, id);
      const res = await Fileinfo({
        path: file,
        container_id: id
      });
      if (res.data.code == 200) {
        let base64String = res.data.data.data.content;
        let decodedstring = window.atob(base64String);
        code.value = decodedstring;
      }
    };
    // 判断文件大小
    const SetWriteInfo = async (path, id) => {
      if (getStringByteLength(code.value) > 3 * 1048576) {
        message("文件内容过大", { type: "success" });
      } else {
        let res = await write({
          path: path,
          content: code.value || " ",
          container_id: id
        });
        if (res.data.code == 200) {
          message("保存成功", { type: "success" });
        }
      }
    };
    return {
      SetWriteInfo,
      getFilinfo,
      code,
      extensions,
      log: console.log
    };
  }
};
</script>

<template>
  <div style="width: 100%">
    <codemirror v-model="code" simple placeholder="Code gose here..." :style="{ height: '550px', width: '100%' }"
      :autofocus="true" :indent-with-tab="true" :tabSize="2" :extensions="extensions" />
  </div>
</template>

<style lang="scss" scoped></style>
